package com.jindy.module.receiptorder.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.jindy.common.core.domain.entity.SysUser;
import com.jindy.common.utils.DateUtils;
import com.jindy.common.utils.SecurityUtils;
import com.jindy.module.constant.StatusConstants;
import com.jindy.module.machine.domain.Machine;
import com.jindy.module.machine.domain.MachineRecord;
import com.jindy.module.machine.mapper.MachineMapper;
import com.jindy.module.machine.mapper.MachineRecordMapper;
import com.jindy.module.product.domain.ProductModel;
import com.jindy.module.product.mapper.ProductMapper;
import com.jindy.module.product.mapper.ProductModelMapper;
import com.jindy.module.receiptorder.domain.ReceiptOrder;
import com.jindy.module.receiptorder.domain.ReceiptOrderProduct;
import com.jindy.module.receiptorder.mapper.ReceiptOrderMapper;
import com.jindy.module.receiptorder.mapper.ReceiptOrderProductMapper;
import com.jindy.module.receiptorder.service.IReceiptOrderService;
import com.jindy.module.stock.domain.Stock;
import com.jindy.module.stock.mapper.StockMapper;
import com.jindy.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 【入库订单】Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-12
 */
@Service
public class ReceiptOrderServiceImpl implements IReceiptOrderService
{
    @Resource
    private ReceiptOrderMapper receiptOrderMapper;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ReceiptOrderProductMapper receiptOrderProductMapper;
    @Resource
    private ProductModelMapper productModelMapper;
    @Resource
    private StockMapper stockMapper;
    @Resource
    private MachineMapper machineMapper;
    @Resource
    private MachineRecordMapper machineRecordMapper;

    /**
     * 查询【入库订单】
     *
     * @param id 【入库订单】主键
     * @return 【入库订单】
     */
    @Override
    public ReceiptOrder selectReceiptOrderById(Long id)
    {
        return receiptOrderMapper.selectReceiptOrderById(id);
    }

    /**
     * 查询【入库订单】列表
     *
     * @param receiptOrder 【入库订单】
     * @return 【入库订单】
     */
    @Override
    public List<ReceiptOrder> selectReceiptOrderList(ReceiptOrder receiptOrder)
    {
        List<ReceiptOrder> list = receiptOrderMapper.selectReceiptOrderList(receiptOrder);
        if(!CollectionUtils.isEmpty(list)){
            list.forEach(or->{
                ReceiptOrderProduct orderProduct = new ReceiptOrderProduct();
                orderProduct.setReceiptOrderId(or.getId());
                List<ReceiptOrderProduct> productList = receiptOrderProductMapper.selectReceiptOrderProductList(orderProduct);
                or.setProductList(productList);
            });
        }
        return list;
    }

    /**
     * 新增【入库订单】
     *
     * @param receiptOrder 【入库订单】
     * @return 结果
     */
    @Override
    @Transactional
    public int insertReceiptOrder(ReceiptOrder receiptOrder)
    {
        SysUser sysUser = sysUserService.selectUserByUserName(SecurityUtils.getUsername());
        receiptOrder.setCreateBy(sysUser.getUserName());
        receiptOrder.setCreateTime(DateUtils.getNowDate());
        // todo 新增订单时默认入库成功，后续流程加了此行代码需要删除
        receiptOrder.setOrderStatus(StatusConstants.ReceiptStatusConstant.deliveryStatus_2);
        int result = receiptOrderMapper.insertReceiptOrder(receiptOrder);
        if(!CollectionUtils.isEmpty(receiptOrder.getProductList())){
            //关联产品
            receiptOrder.getProductList().forEach(orderProduct -> {
                orderProduct.setReceiptOrderId(receiptOrder.getId());
                //orderProduct.setWarehousingWarehouseId(receiptOrder.getWarehousingWarehouseId());
                //orderProduct.setWarehousingWarehouseName(receiptOrder.getWarehousingWarehouseName());
            });
            receiptOrderProductMapper.insertReceiptOrderProducts(receiptOrder.getProductList());

            updateStock(receiptOrder,receiptOrder.getProductList());
        }

        return result;
    }

    /**
     * 入库成功
     */
    private void updateStock(ReceiptOrder receiptOrder,List<ReceiptOrderProduct> productList){
        for(ReceiptOrderProduct product:productList){
            // 1:修改产品-模型中的数量
            ProductModel productModel = new ProductModel();
            BeanUtils.copyProperties(product,productModel);
            productModel = productModelMapper.selectProductModel(productModel);
            productModel.setQuantity(productModel.getQuantity()+product.getReceiptQuantity());
            productModelMapper.updateProductModel(productModel);

            // 2:查询库存中是否有次产品-模型记录
            Stock stock = new Stock();
            BeanUtils.copyProperties(product,stock);
            stock.setWarehouseId(product.getWarehousingWarehouseId());
            List<Stock> stocks = stockMapper.selectStockList(stock);
            if(CollectionUtils.isEmpty(stocks)){
                // 3:库存中没有此及， 则添加一条
                stock.setWarehouseName(product.getWarehousingWarehouseName());
                stock.setQuantity(product.getReceiptQuantity());
                stock.setAvailableQuantity(product.getReceiptQuantity());
                stockMapper.insertStock(stock);
            }else{
                // 4:库存中有此记录，则修改数量
                stock=stocks.get(0);
                stock.setQuantity(stock.getQuantity()+product.getReceiptQuantity());
                stock.setAvailableQuantity(stock.getAvailableQuantity()+product.getReceiptQuantity());
                // TODO: 2022/10/14 检查单走后需要修改一下可用数量
                stockMapper.updateStock(stock);
            }

            // 5：给入库的每台机子生成编码
            List<Machine> machines = new ArrayList<>();
            // 6.给机器添加入库记录
            List<MachineRecord> machineRecords = new ArrayList<>();
            for(int i=0;i<product.getReceiptQuantity();i++){
                Machine machine = new Machine();
                machine.setId(UUID.randomUUID().toString().replaceAll("-",""));
                machine.setProductId(product.getProductId());
                machine.setProductNo(product.getProductNo());
                machine.setProductName(product.getProductName());
                machine.setModel(product.getModel());
                machine.setWarehouseId(product.getWarehousingWarehouseId());
                machine.setWarehouseName(product.getWarehousingWarehouseName());
                machine.setStartWarehouseId(product.getWarehousingWarehouseId());//初始仓库
                machine.setStartWarehouseName(product.getWarehousingWarehouseName());
                machine.setReceiptId(receiptOrder.getId());
                //编号
                machine.setMachineNo(UUID.randomUUID().toString().replaceAll("-",""));
                machine.setWarehousingTime(receiptOrder.getWarehousingTime());
                machines.add(machine);

                MachineRecord record = new MachineRecord();
                record.setWarehousingId(receiptOrder.getId());
                record.setWarehousingNo(receiptOrder.getWarehousingNo());
                record.setWarehousingTime(receiptOrder.getWarehousingTime());
                record.setMachineId(machine.getId());
                record.setMachineNo(machine.getMachineNo());
                record.setWarehouseId(machine.getWarehouseId());
                record.setWarehouseName(machine.getWarehouseName());
                machineRecords.add(record);
            }
            machineMapper.insertMachines(machines);
            machineRecordMapper.insertMachineRecords(machineRecords);
        }


    }

    /**
     * 修改【入库订单】
     *
     * @param receiptOrder 【入库订单】
     * @return 结果
     */
    @Override
    public int updateReceiptOrder(ReceiptOrder receiptOrder)
    {
        SysUser sysUser = sysUserService.selectUserByUserName(SecurityUtils.getUsername());
        receiptOrder.setUpdateBy(sysUser.getUserName());
        receiptOrder.setUpdateTime(DateUtils.getNowDate());
        //删除订单关联的产品
        receiptOrderProductMapper.deleteOrderProductByOrderId(receiptOrder.getId());
        if(!CollectionUtils.isEmpty(receiptOrder.getProductList())){
            //关联产品
            receiptOrder.getProductList().forEach(orderProduct -> {
                orderProduct.setReceiptOrderId(receiptOrder.getId());
                //orderProduct.setWarehousingWarehouseId(receiptOrder.getWarehousingWarehouseId());
                //orderProduct.setWarehousingWarehouseName(receiptOrder.getWarehousingWarehouseName());
            });
            receiptOrderProductMapper.insertReceiptOrderProducts(receiptOrder.getProductList());
        }
        return receiptOrderMapper.updateReceiptOrder(receiptOrder);
    }

    /**
     * 批量删除【入库订单】
     *
     * @param ids 需要删除的【入库订单】主键
     * @return 结果
     */
    @Override
    public int deleteReceiptOrderByIds(Long[] ids)
    {
        return receiptOrderMapper.deleteReceiptOrderByIds(ids);
    }

    /**
     * 删除【入库订单】信息
     *
     * @param id 【入库订单】主键
     * @return 结果
     */
    @Override
    public int deleteReceiptOrderById(Long id)
    {
        return receiptOrderMapper.deleteReceiptOrderById(id);
    }
}
